package com.steven.ourcontest.login.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.login.api.LoginApi
import com.steven.ourcontest.login.bean.CodeResponse
import com.steven.ourcontest.login.bean.LoginResponse
import com.steven.ourcontest.login.bean.SignUpResponse
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*
import kotlin.math.pow

class LoginViewModel : BaseViewModel() {
    private val _codeResponse = MutableLiveData<CodeResponse?>()
    val codeResponse: LiveData<CodeResponse?>
        get() = _codeResponse

    private val _loginResponse = MutableLiveData<LoginResponse?>()
    val loginResponse: LiveData<LoginResponse?>
        get() = _loginResponse

    private val _signUpResponse = MutableLiveData<SignUpResponse?>()
    val signUpResponse: LiveData<SignUpResponse?>
        get() = _signUpResponse

    var lastSendCodeEmail = ""
    fun sendCode(email: String) {
        val random = Random()
        var code = 0
        for (i in 0 until 4) {
            code += (random.nextInt(8) + 1) * 10.0.pow(i).toInt()
        }
        disposed += LoginApi.instance.sendCode(email, code)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                lastSendCodeEmail = email
                _codeResponse.value = it.result
                LoginController.lastSendCode = code
            }, {
                it.printStackTrace()
            })
    }

    fun quickLogin(email: String) {
        disposed += LoginApi.instance.quickLogin(email)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _loginResponse.value = it.result
            }, {
                it.printStackTrace()
            })
    }

    fun login(email: String, password: String) {
        disposed += LoginApi.instance.login(email, password)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _loginResponse.value = it.result
            }, {
                it.printStackTrace()
            })
    }

    fun signUp(email: String, password: String) {
        disposed += LoginApi.instance.signUp(email, password)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _signUpResponse.value = it.result
            }, {
                it.printStackTrace()
            })
    }
}


